package com.wilmer.stemCourseCon.service.impl;

import com.wilmer.common.annotation.DataScope;
import com.wilmer.common.constant.UserConstants;
import com.wilmer.common.core.domain.entity.SysDept;
import com.wilmer.common.core.domain.entity.SysRole;
import com.wilmer.common.core.domain.entity.SysUser;
import com.wilmer.common.core.text.Convert;
import com.wilmer.common.exception.ServiceException;
import com.wilmer.common.utils.SecurityUtils;
import com.wilmer.common.utils.StringUtils;
import com.wilmer.common.utils.spring.SpringUtils;
import com.wilmer.stemCourseCon.domain.StemCourseCon;
import com.wilmer.stemCourseCon.domain.TreeSelect2;
import com.wilmer.stemCourseCon.mapper.StemCourseConMapper;
import com.wilmer.stemCourseCon.service.StemCourseConService;
import com.wilmer.system.mapper.SysDeptMapper;
import com.wilmer.system.mapper.SysRoleMapper;
import com.wilmer.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class StemCourseConServiceImpl implements StemCourseConService {
    @Autowired
    private StemCourseConMapper stemCourseConMapper;


    @Override
    public List<StemCourseCon> selectStemCourseConList(StemCourseCon stemCourseCon) {
        return stemCourseConMapper.selectStemCourseConList(stemCourseCon);
    }

    /**
     * 查询课程结构树结构信息
     */
    @Override
    public List<TreeSelect2> selectStemCourseConTreeList(StemCourseCon stemCourseCon) {
//        List<StemCourseCon> stemCourseCons = SpringUtils.getAopProxy(this).selectStemCourseConList(stemCourseCon);
        List<StemCourseCon> stemCourseCons =selectStemCourseConList(stemCourseCon);
        return buildStemCourseConTreeSelect(stemCourseCons);
    }

    /**
     * 构建前端所需要树结构
     *
     */
    @Override
    public List<StemCourseCon> buildStemCourseConTree(List<StemCourseCon> stemCourseCons) {
        List<StemCourseCon> returnList = new ArrayList<StemCourseCon>();
        List<Long> tempList = stemCourseCons.stream().map(StemCourseCon::getConId).collect(Collectors.toList());
        for (StemCourseCon stemCourseCon : stemCourseCons) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(stemCourseCon.getParentId())) {
                recursionFn(stemCourseCons, stemCourseCon);
                returnList.add(stemCourseCon);
            }
        }
        if (returnList.isEmpty()) {
            returnList = stemCourseCons;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     */
    @Override
    public List<TreeSelect2> buildStemCourseConTreeSelect(List<StemCourseCon> stemCourseCons) {
        List<StemCourseCon> deptTrees = buildStemCourseConTree(stemCourseCons);
        return deptTrees.stream().map(TreeSelect2::new).collect(Collectors.toList());
    }

//    /**
//     *
//     *
//     */
//    @Override
//    public List<Long> selectDeptListByRoleId(Long roleId) {
//        SysRole role = roleMapper.selectRoleById(roleId);
//        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
//    }

    /**
     * 根据课程结构ID查询信息
     */
    @Override
    public StemCourseCon selectStemCourseConById(Long stemCourseConId) {
        return stemCourseConMapper.selectStemCourseConById(stemCourseConId);
    }

    /**
     * 根据ID查询所有子课程结构（正常状态）
     */
    @Override
    public int selectNormalChildrenStemCourseConById(Long stemCourseConId) {
        return stemCourseConMapper.selectNormalChildrenStemCourseConById(stemCourseConId);
    }

    /**
     * 是否存在子节点
     *
     */
    @Override
    public boolean hasChildByStemCourseConId(Long stemCourseConId) {
        int result = stemCourseConMapper.hasChildByStemCourseConId(stemCourseConId);
        return result > 0;
    }

    /**
     * 查询课程结构是否存在课程
     *
     */
    @Override
    public boolean checkStemCourseConExistUser(Long stemCourseConId) {
        int result = stemCourseConMapper.checkStemCourseConExistUser(stemCourseConId);
        return result > 0;
    }

    /**
     * 校验课程结构名称是否唯一
     *
     */
    @Override
    public boolean checkStemCourseConNameUnique(StemCourseCon stemCourseCon) {
        Long stemCourseConId = StringUtils.isNull(stemCourseCon.getConId()) ? -1L : stemCourseCon.getConId();
        StemCourseCon info = stemCourseConMapper.checkStemCourseConNameUnique(stemCourseCon.getConName(), stemCourseCon.getParentId());
        if (StringUtils.isNotNull(info) && info.getConId().longValue() != stemCourseConId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验课程结构是否有数据权限
     *
     */
    @Override
    public void checkStemCourseConDataScope(Long stemCourseConId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            StemCourseCon stemCourseCon = new StemCourseCon();
            stemCourseCon.setConId(stemCourseConId);
            List<StemCourseCon> stemCourseCons = SpringUtils.getAopProxy(this).selectStemCourseConList(stemCourseCon);
            if (StringUtils.isEmpty(stemCourseCons)) {
                throw new ServiceException("没有权限访问课程结构数据！");
            }
        }
    }

    /**
     * 新增保存课程结构信息
     *
     */
    @Override
    public int insertStemCourseCon(StemCourseCon stemCourseCon) {
        StemCourseCon info = stemCourseConMapper.selectStemCourseConById(stemCourseCon.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("课程结构停用，不允许新增");
        }
        stemCourseCon.setAncestors(info.getAncestors() + "," + stemCourseCon.getParentId());
        return stemCourseConMapper.insertStemCourseCon(stemCourseCon);
    }

    /**
     * 修改保存课程结构信息
     *
     */
    @Override
    public int updateStemCourseCon(StemCourseCon stemCourseCon) {
        StemCourseCon newParentStemCourseCon = stemCourseConMapper.selectStemCourseConById(stemCourseCon.getParentId());
        StemCourseCon oldStemCourseCon = stemCourseConMapper.selectStemCourseConById(stemCourseCon.getConId());
        if (StringUtils.isNotNull(newParentStemCourseCon) && StringUtils.isNotNull(oldStemCourseCon)) {
            String newAncestors = newParentStemCourseCon.getAncestors() + "," + newParentStemCourseCon.getConId();
            String oldAncestors = oldStemCourseCon.getAncestors();
            stemCourseCon.setAncestors(newAncestors);
            updateStemCourseConChildren(stemCourseCon.getConId(), newAncestors, oldAncestors);
        }
        int result = stemCourseConMapper.updateStemCourseCon(stemCourseCon);
        if (UserConstants.DEPT_NORMAL.equals(stemCourseCon.getStatus()) && StringUtils.isNotEmpty(stemCourseCon.getAncestors())
                && !StringUtils.equals("0", stemCourseCon.getAncestors())) {
            // 如果该课程结构是启用状态，则启用该课程结构的所有上级课程结构
            updateParentStemCourseConStatusNormal(stemCourseCon);
        }
        return result;
    }


    private void updateParentStemCourseConStatusNormal(StemCourseCon stemCourseCon) {
        String ancestors = stemCourseCon.getAncestors();
        Long[] stemCourseConIds = Convert.toLongArray(ancestors);
        stemCourseConMapper.updateStemCourseConStatusNormal(stemCourseConIds);
    }

    /**
     * 修改子元素关系
     *
     */
    public void updateStemCourseConChildren(Long stemCourseConId, String newAncestors, String oldAncestors) {
        List<StemCourseCon> children = stemCourseConMapper.selectChildrenStemCourseConById(stemCourseConId);
        for (StemCourseCon child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            stemCourseConMapper.updateStemCourseConChildren(children);
        }
    }

    /**
     * 删除课程结构管理信息
     *
     */
    @Override
    public int deleteStemCourseConById(Long stemCourseConId) {
        return stemCourseConMapper.deleteStemCourseConById(stemCourseConId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<StemCourseCon> list, StemCourseCon t) {
        // 得到子节点列表
        List<StemCourseCon> childList = getChildList(list, t);
        t.setChildren(childList);
        for (StemCourseCon tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<StemCourseCon> getChildList(List<StemCourseCon> list, StemCourseCon t) {
        List<StemCourseCon> tlist = new ArrayList<StemCourseCon>();
        Iterator<StemCourseCon> it = list.iterator();
        while (it.hasNext()) {
            StemCourseCon n = (StemCourseCon) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getConId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<StemCourseCon> list, StemCourseCon t) {
        return getChildList(list, t).size() > 0;
    }
}
